﻿<%@ WebHandler Language="C#" Class="list" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Text;
using System.Data.OracleClient;
using System.Net.Mail;
using System.Net;
using System.Web.Script.Serialization;


public class list : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    private StringBuilder sb = null;
    public DataSet ds = null;
    public DataTable dt = null;
    private string sqlwhere = "";
    public void ProcessRequest(HttpContext context)
    {
        string type = PageBase.ext_string(context.Request.Params["type"]);
        switch (type)
        {
            case "get_myinfo":
                get_myinfo(context);
                break;

            default:
                //getinfo(context);
                break;
        }
    }
    //获取返回消息
    public void get_myinfo(HttpContext context)
    {
        string jxsname = "";
        string jxsye = "";
        bool flag=false;
        string mobile = PageBase.ext_string(context.Request.Params["mobiles"]);
        string sqllist = @"select username,loginid from [dbo].[sys_users] where  phone='{0}' and ltrim(rtrim(isactive))='Y'";
        sqllist = string.Format(sqllist,mobile);
        DataTable dtResult = DBHelper.ExecuteDataTable(sqllist);
        if (dtResult.Rows.Count > 0)
        {
            flag = true;
            jxsname = dtResult.Rows[0]["username"].ToString();
            string sqlye = "exec [zdy_查询经销商余额] '{0}'";
            sqlye = string.Format(sqlye, dtResult.Rows[0]["loginid"].ToString());
            DataTable dtye = DBHelper.ExecuteDataTable(sqlye);
            if (dtye.Rows.Count > 0)
            {
                jxsye = dtye.Rows[0]["FEECANTAKE"].ToString();
            }

        }
        else
        {
            flag = false;
            jxsname = "查询失败，请联系管理员";
        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + jxsname + "\",\"jxsye\":\"" + jxsye + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //提交发货信息
    public void save_fhinfo(HttpContext context)
    {
        string msg = "";
        string sqlsave = "";
        bool flag=false;
        GetDate list = new GetDate();
        using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream))
        {
            string s = sr.ReadToEnd();
            list = new JavaScriptSerializer().Deserialize<GetDate>(s);
        }
        if (list.ArrayObj_main.Count > 0)
        {
            string docno = Utility.Trim(list.ArrayObj_main[0].DOCNO);
            string txt_kdgs = Utility.Trim(list.ArrayObj_main[0].TXT_KDGS);
            string txt_kddh = Utility.Trim(list.ArrayObj_main[0].TXT_KDDH);
            string txt_kdfhr = Utility.Trim(list.ArrayObj_main[0].TXT_KDFHR);
            string txt_kdtel = Utility.Trim(list.ArrayObj_main[0].TXT_KDTEL);

            string sqlfb = "exec [zdy_调拨发货] '{0}','{1}','{2}','{3}','{4}'";
            sqlfb = string.Format(sqlfb, docno,txt_kdgs,txt_kddh,txt_kdfhr,txt_kdtel);
            DataTable dtfb = DBHelper.ExecuteDataTable(sqlfb);

            if (dtfb.Rows.Count > 0)
            {
                if (dtfb.Rows[0]["zt"].ToString() == "成功")
                {
                    flag = true;
                    msg = dtfb.Rows[0]["remsg"].ToString();
                }
                else
                {
                    flag = false;
                    msg = dtfb.Rows[0]["remsg"].ToString();
                }
            }
            else
            {
                flag = false;
                msg = "失败，请联系管理员！";
            }

        }

        else
        {
            flag = false;
            msg = "失败，请联系管理员！";
        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }



    //获取发货列表
    public void get_deliver_list(HttpContext context)
    {
        string customerCode = PageBase.ext_string(context.Request.Params["customerCodes"]);
        string mobile= PageBase.ext_string(context.Request.Params["mobiles"]);
        string lxs= PageBase.ext_string(context.Request.Params["lxs"]);
        string sqllist = "";
        if (lxs == "Snatch")
        {
            sqllist = @" select a.id,a.requestdocno,a.docno,a.buy_takeman,a.buy_taketel,a.buy_takeaddress,d.username buyusername,
f.username saleusername,a.sale_kdgs,a.sale_kddjbh,a.sale_kdlxr,a.sale_kdtel,c.value,c.name,c.yscode+c.ysname ys,c.cmwm,
case a.status when 0 then '待发货' when 1 then '处理中' when 90 then '失败' when 99 then '完成' else '' end zt,b.sl,a.createtime,k.createtime requesttime
 from t_transferDeliver_main a left join t_transferDeliver_mx b on a.docno=b.docno
 left join [t_product] c on b.tmid=c.id 
 left join sys_users d on a.buy_mobile=d.phone
 left join sys_users f on a.sale_mobile=f.phone
 left join [t_transferRequest_main] k on a.requestdocno=k.docno
 where a.sale_mobile='{0}' and ltrim(rtrim(a.isactive))='Y'
 order by a.createtime desc";
        }
        else if (lxs == "Request")
        {
            sqllist = @" select a.id,a.requestdocno,a.docno,a.buy_takeman,a.buy_taketel,a.buy_takeaddress,d.username buyusername,
f.username saleusername,a.sale_kdgs,a.sale_kddjbh,a.sale_kdlxr,a.sale_kdtel,c.value,c.name,c.yscode+c.ysname ys,c.cmwm,
case a.status when 0 then '待发货' when 1 then '处理中' when 90 then '失败' when 99 then '完成' else '' end zt,b.sl,a.createtime,k.createtime requesttime
 from t_transferDeliver_main a left join t_transferDeliver_mx b on a.docno=b.docno
 left join [t_product] c on b.tmid=c.id 
 left join sys_users d on a.buy_mobile=d.phone
 left join sys_users f on a.sale_mobile=f.phone
 left join [t_transferRequest_main] k on a.requestdocno=k.docno
 where a.buy_mobile='{0}' and ltrim(rtrim(a.isactive))='Y'
 order by a.createtime desc";
        }


        sqllist = string.Format(sqllist,mobile);
        DataTable dtResult = DBHelper.ExecuteDataTable(sqllist);
        sb = new StringBuilder();
        sb.Append("{\"item\":[");
        for (int i = 0; i < dtResult.Rows.Count; i++)
        {
            sb.Append("{\"docno\":\"" + dtResult.Rows[i]["docno"].ToString() + "\",");
            sb.Append("\"requestdocno\":\"" + dtResult.Rows[i]["requestdocno"].ToString() + "\",");
            sb.Append("\"id\":\"" + dtResult.Rows[i]["id"].ToString() + "\",");
            sb.Append("\"value\":\"" + dtResult.Rows[i]["value"].ToString() + "\",");
            sb.Append("\"name\":\"" + dtResult.Rows[i]["name"].ToString() + "\",");
            sb.Append("\"ys\":\"" + dtResult.Rows[i]["ys"].ToString() + "\",");
            sb.Append("\"cmwm\":\"" + dtResult.Rows[i]["cmwm"].ToString() + "\",");
            sb.Append("\"docno\":\"" + dtResult.Rows[i]["docno"].ToString() + "\",");
            sb.Append("\"takeman\":\"" + dtResult.Rows[i]["buy_takeman"].ToString() + "\",");
            sb.Append("\"takephone\":\"" + dtResult.Rows[i]["buy_taketel"].ToString() + "\",");
            sb.Append("\"takeaddress\":\"" + dtResult.Rows[i]["buy_takeaddress"].ToString() + "\",");
            sb.Append("\"buyusername\":\"" + dtResult.Rows[i]["buyusername"].ToString() + "\",");
            sb.Append("\"saleusername\":\"" + dtResult.Rows[i]["saleusername"].ToString() + "\",");
            sb.Append("\"sale_kdgs\":\"" + dtResult.Rows[i]["sale_kdgs"].ToString() + "\",");
            sb.Append("\"sale_kddjbh\":\"" + dtResult.Rows[i]["sale_kddjbh"].ToString() + "\",");
            sb.Append("\"sale_kdlxr\":\"" + dtResult.Rows[i]["sale_kdlxr"].ToString() + "\",");
            sb.Append("\"sale_kdtel\":\"" + dtResult.Rows[i]["sale_kdtel"].ToString() + "\",");
            sb.Append("\"zt\":\"" + dtResult.Rows[i]["zt"].ToString() + "\",");
            sb.Append("\"sl\":\"" + dtResult.Rows[i]["sl"].ToString() + "\",");
            sb.Append("\"requesttime\":\"" + dtResult.Rows[i]["requesttime"].ToString() + "\",");
            sb.Append("\"createtime\":\"" + dtResult.Rows[i]["createtime"].ToString() + "\"}");
            if (i < dtResult.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //查询尺码下拉选项
    public void getkdgs(HttpContext context)
    {
        string sql = @"select id,typename from t_type where typelx='快递公司' and isactive='Y' order by xh ";
        DataTable dt = DBHelper.ExecuteDataTable(sql);

        string fsmessage = "";
        sb = new StringBuilder();
        string code = "0";
        string msg = "";
        sb.Append("{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\",\"data\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            sb.Append("{\"id\":\"" + dt.Rows[i]["id"].ToString() + "\"");
            sb.Append(",\"typename\":\"" + dt.Rows[i]["typename"] + "\"}");
            if (i < dt.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //删除
    public void delete(HttpContext context)
    {
        string getids = PageBase.ext_string(context.Request.Params["getids"]);
        string msg = "";
        bool flag;
        string sqldelete = "update [t_transferRequest_main] set isactive='N' where id={0}";
        sqldelete = string.Format(sqldelete, getids);
        int dtcount= DBHelper.ExecuteNonQuery(sqldelete);
        if (dtcount > 0)
        {
            flag = true;
            msg = "作废成功";
        }
        else
        {
            flag = false;
            msg = "作废失败";
        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //获取修改明细
    public void getinfo_byids(HttpContext context)
    {
        string ids = PageBase.ext_string(context.Request.Params["ids"]);
        //主表
        string sqlmain = @"select a.id,a.docno,a.mobile,a.request_storecode,b.username,a.takeman,
         a.takephone,a.takeaddress,a.remark from [t_transferRequest_main] a
         left join [sys_users] b on a.request_storecode=b.loginid and a.mobile=b.phone
         where a.id='{0}' and ltrim(rtrim(a.isactive))='Y' ";
        sqlmain = string.Format(sqlmain,ids);
        DataTable dtmain = DBHelper.ExecuteDataTable(sqlmain);
        //明细表
        string sqlmx = @"select a.id,b.no,a.tmid,a.sl from [t_transferRequest_mx] a left join t_product b
         on a.tmid=b.id  where docno='{0}' order by a.id ";
        sqlmx = string.Format(sqlmx,dtmain.Rows[0]["docno"].ToString());
        DataTable dtmx = DBHelper.ExecuteDataTable(sqlmx);

        sb = new StringBuilder();
        sb.Append("{\"itemMain\":[");
        for (int i = 0; i < dtmain.Rows.Count; i++)
        {
            string storename = dtmain.Rows[i]["request_storecode"].ToString() + "[" + dtmain.Rows[i]["username"].ToString() +"]";
            sb.Append("{\"id\":\"" + dtmain.Rows[i]["id"].ToString() + "\",");
            sb.Append("\"storename\":\"" + storename + "\",");
            sb.Append("\"docno\":\"" + dtmain.Rows[i]["docno"].ToString() + "\",");
            sb.Append("\"mobile\":\"" + dtmain.Rows[i]["mobile"].ToString() + "\",");
            sb.Append("\"request_storecode\":\"" + dtmain.Rows[i]["request_storecode"].ToString() + "\",");
            sb.Append("\"takeman\":\"" + dtmain.Rows[i]["takeman"].ToString() + "\",");
            sb.Append("\"takephone\":\"" + dtmain.Rows[i]["takephone"].ToString() + "\",");
            sb.Append("\"takeaddress\":\"" + dtmain.Rows[i]["takeaddress"].ToString() + "\",");
            sb.Append("\"remark\":\"" + dtmain.Rows[i]["remark"].ToString().Replace(',', '，').Replace('{', '(').Replace('}', ')').Replace('[', '(').Replace(']', ')').Replace('"', ' ').Replace('：', ':') + "\"}");
            if (i < dtmain.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("],");
        sb.Append("\"itemMx\":[");
        for (int j = 0; j < dtmx.Rows.Count; j++)
        {
            sb.Append("{\"id\":\"" + dtmx.Rows[j]["id"].ToString() + "\",");
            sb.Append("\"no\":\"" + dtmx.Rows[j]["no"].ToString() + "\",");
            sb.Append("\"tmid\":\"" + dtmx.Rows[j]["tmid"].ToString() + "\",");
            sb.Append("\"sl\":\"" + dtmx.Rows[j]["sl"].ToString() + "\"}");
            if (j < dtmx.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //修改
    public void editbydocno(HttpContext context)
    {
        string msg = "";
        string sqlsave = "";
        bool flag=false;
        string lx = Utility.Trim(context.Request.Params["lxs"]); //类型
        GetDate list = new GetDate();
        using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream))
        {
            string s = sr.ReadToEnd();
            list = new JavaScriptSerializer().Deserialize<GetDate>(s);
        }
        if (list.ArrayObj_main.Count > 0)
        {
            string id = Utility.Trim(list.ArrayObj_main[0].ID);
            string docno = Utility.Trim(list.ArrayObj_main[0].DOCNO);
            string shr = Utility.Trim(list.ArrayObj_main[0].SHR);
            string phone = Utility.Trim(list.ArrayObj_main[0].PHONE);
            string address = Utility.Trim(list.ArrayObj_main[0].ADDRESS);
            string remark = Utility.Trim(list.ArrayObj_main[0].REMARK);
            string customercode = Utility.Trim(list.ArrayObj_main[0].CUSTOMERCODE);
            int status = 0;
            if (lx == "save")
            {
                flag = true;
                status = 0;
            }
            else{
                string sqlye = "exec [zdy_查询经销商余额] '{0}'";
                sqlye = string.Format(sqlye, customercode);
                DataTable dtye = DBHelper.ExecuteDataTable(sqlye);
                if (dtye.Rows.Count > 0)
                {
                    if (Utility.ToDecimal(dtye.Rows[0]["FEECANTAKE"].ToString()) > 0)
                    {
                        status = 1;
                        flag = true;
                    }
                    else
                    {
                        flag = false;
                        msg = "当前可提货金额为:"+dtye.Rows[0]["FEECANTAKE"].ToString()+"，无法发布，请先保存！";
                    }
                }
                else
                {
                    flag = false;
                    msg = "未查到该经销商余额，请联系管理员！";
                }
            }
            if (flag == true)
            {
                //主体信息
                sqlsave = @"update [t_transferRequest_main] set
                            [takeman]='{0}'
                           ,[takephone]='{1}'
                           ,[takeaddress]='{2}'
                           ,[remark]='{3}'
                           ,[status]={4}
                           ,[updatetime]='{5}'
                           where id={6};";
                sqlsave = string.Format(sqlsave, shr, phone, address, remark, status, DateTime.Now.ToString(), id);
                if (list.ArrayObj_mx.Count > 0)
                {
                    DBHelper.ExecuteNonQuery("delete from t_transferRequest_mx where docno='" + docno + "'");
                    //明细
                    for (int i = 0; i < list.ArrayObj_mx.Count; i++)
                    {
                        sqlsave += @"insert into t_transferRequest_mx(  docno, tmid, sl, isactive, createtime) values
                    ('{0}','{1}','{2}','{3}','{4}');";
                        string tmid = Utility.Trim(list.ArrayObj_mx[i].TMID);
                        Int32? sl = Utility.ToInt(Utility.Trim(list.ArrayObj_mx[i].SL));
                        sqlsave = string.Format(sqlsave, docno, tmid, sl, 'Y', DateTime.Now.ToString());
                    }
                }
                //插入数据库条数
                int zxcount = 0;
                try
                {
                    zxcount = DBHelper.ExecuteNonQuery(sqlsave);
                }
                catch (Exception e)
                {
                    flag = false;
                    msg = e.Message;
                }
                //计算前台传过来的数据条数
                int zqts = list.ArrayObj_main.Count + list.ArrayObj_mx.Count;
                if (zxcount == zqts)
                {
                    if (lx == "save")
                    {
                        flag = true;
                        msg = "保存成功！";
                    }
                    else
                    {
                        flag = true;
                        msg = "发布成功，等待系统处理！";
                        string sqlfb = "exec [zdy_处理发布订单] '{0}'";
                        sqlfb = string.Format(sqlfb, docno);
                        DataTable dtfb = DBHelper.ExecuteDataTable(sqlfb);
                    }
                }
                else
                {
                    if (lx == "save")
                    {
                        flag = false;
                        msg = "保存失败，请联系管理员！";
                    }
                    else
                    {
                        flag = false;
                        msg = "发布失败，请联系管理员！";
                    }
                }
            }
        }
        else
        {
            flag = false;
            msg = "失败，请联系管理员！";
        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //调拨申请保存或者发布
    public void requestsaveandtj(HttpContext context)
    {
        string msg = "";
        string sqlsave = "";
        bool flag=false;
        string djbhs = PageBase.ext_string(context.Request.Params["djbhs"]);
        if (djbhs != "")
        {
            string del = @"delete from [t_transferRequest_main] where docno='{0}';delete from [t_transferRequest_mx] where docno='{0}';";
            del = string.Format(del, djbhs);
            DBHelper.ExecuteNonQuery(del);
        }
        //生成单号
        string sqldjbh = @"declare @BH INT;declare @MID varchar(50);SELECT @BH=ISNULL(MAX(RIGHT(docno,4)),0)+1 FROM 
                         t_transferRequest_main WHERE LEFT(docno,2)='TF' AND  RIGHT(LEFT(docno,8),6)=CONVERT(VARCHAR(10),GETDATE(),12);
                         set @MID='TF'+CONVERT(VARCHAR(10),GETDATE(),12)+CAST(right((10000+@BH),4) AS VARCHAR(20)) ;
                         SELECT @MID";
        DataTable dtResult = DBHelper.ExecuteDataTable(sqldjbh);
        string djbh = dtResult.Rows[0][0].ToString();
        string lx = Utility.Trim(context.Request.Params["lxs"]); //类型

        GetDate list = new GetDate();
        using (System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream))
        {
            string s = sr.ReadToEnd();
            list = new JavaScriptSerializer().Deserialize<GetDate>(s);
        }
        if (list.ArrayObj_main.Count > 0)
        {
            string customercode = Utility.Trim(list.ArrayObj_main[0].CUSTOMERCODE);
            string shr = Utility.Trim(list.ArrayObj_main[0].SHR);
            string phone = Utility.Trim(list.ArrayObj_main[0].PHONE);
            string address = Utility.Trim(list.ArrayObj_main[0].ADDRESS);
            string remark = Utility.Trim(list.ArrayObj_main[0].REMARK);
            string mobile = Utility.Trim(list.ArrayObj_main[0].MOBILE);
            int status = 0;
            if (lx == "save")
            {
                flag = true;
                status = 0;
            }

            else{
                string sqlye = "exec [zdy_查询经销商余额] '{0}'";
                sqlye = string.Format(sqlye, customercode);
                DataTable dtye = DBHelper.ExecuteDataTable(sqlye);
                if (dtye.Rows.Count > 0)
                {
                    if (Utility.ToDecimal(dtye.Rows[0]["FEECANTAKE"].ToString()) > 0)
                    {
                        status = 1;
                        flag = true;
                    }
                    else
                    {
                        flag = false;
                        msg = "当前可提货金额不足，无法发布，请先保存！";
                    }
                }
                else
                {
                    flag = false;
                    msg = "未查到该经销商余额，请联系管理员！";
                }
            }
            if (flag == true)
            {
                //主体信息
                sqlsave = @"INSERT INTO [t_transferRequest_main]( docno, request_storecode, takeman, takephone, takeaddress, kdlx, 
                                 iscf, remark, status, isactive, creater, createtime, updater, updatetime,mobile)
                        VALUES
                       ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}');";
                sqlsave = string.Format(sqlsave, djbh, customercode, shr, phone, address, 0, 0, remark, status, 'Y', customercode, DateTime.Now.ToString(), customercode,
                                       DateTime.Now.ToString(), mobile);
                //明细
                for (int i = 0; i < list.ArrayObj_mx.Count; i++)
                {
                    sqlsave += @"insert into t_transferRequest_mx(docno, tmid, sl, isactive, createtime) values
                    ('{0}','{1}','{2}','{3}','{4}');";
                    string tmid = Utility.Trim(list.ArrayObj_mx[i].TMID);
                    Int32? sl = Utility.ToInt(Utility.Trim(list.ArrayObj_mx[i].SL));
                    sqlsave = string.Format(sqlsave, djbh, tmid, sl, 'Y', DateTime.Now.ToString());
                }
                //插入数据库条数
                int zxcount = 0;
                try
                {
                    zxcount = DBHelper.ExecuteNonQuery(sqlsave);
                }
                catch (Exception e)
                {
                    flag = false;
                    msg = e.Message;
                }
                //计算前台传过来的数据条数
                int zqts = list.ArrayObj_main.Count + list.ArrayObj_mx.Count;
                if (zxcount == zqts)
                {
                    if (lx == "save")
                    {
                        flag = true;
                        msg = "保存成功！";
                    }
                    else
                    {
                        flag = true;
                        msg = "发布成功，等待系统处理！";
                        string sqlfb = "exec [zdy_处理发布订单] '{0}'";
                        sqlfb = string.Format(sqlfb, djbh);
                        DataTable dtfb = DBHelper.ExecuteDataTable(sqlfb);
                    }
                }
                else
                {
                    if (lx == "save")
                    {
                        flag = false;
                        msg = "保存失败，请联系管理员！";
                    }
                    else
                    {
                        flag = false;
                        msg = "发布失败，请联系管理员！";
                    }
                }
            }
        }
        else
        {
            flag = false;
            msg = "失败，请联系管理员！";
        }
        context.Response.Write("{\"flag\":\"" + flag + "\",\"remsg\":\"" + msg + "\",\"djbh\":\"" + djbh + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //验证条码
    public void gettm(HttpContext context)
    {
        string tm = Utility.Trim(context.Request.Params["tms"]); //货号
        try
        {
            string sqlview = "[dbo].[zdy_查询条码信息] '{0}'";
            sqlview = string.Format(sqlview,tm);
            dt = DBHelper.ExecuteDataTable(sqlview) ;
            if (dt.Rows[0]["remsg"].ToString()=="成功")
            {
                context.Response.Write("{\"flag\":true,\"msg\":\"" + dt.Rows[0]["remsg"].ToString() + "\",\"tmid\":\"" + dt.Rows[0]["tmid"].ToString() + "\",\"bjtm\":\"" + dt.Rows[0]["bjtm"].ToString() + "\"}");
            }
            else
            {
                context.Response.Write("{\"flag\":false,\"msg\":\"" + dt.Rows[0]["remsg"].ToString() + "\"}");
            }
        }
        catch (Exception ex)
        {
            context.Response.Write("{\"flag\":false,\"msg\":\"" + ex + "\"}");
        }
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //根据经销商编号获取地址联系人电话
    public void get_address_bycode(HttpContext context)
    {
        string customerCode = PageBase.ext_string(context.Request.Params["customerCodes"]);
        string mobile = PageBase.ext_string(context.Request.Params["mobiles"]);
        string sqllist = @"select a.loginid,a.username,a.customername,a.phone,b.storeaddress from sys_users a 
                           left join [t_addressList] b on a.loginid=b.code
                           where ltrim(rtrim(a.isactive))='Y' and a.loginid='{0}' and a.phone='{1}'";
        sqllist = string.Format(sqllist,customerCode,mobile);
        DataTable dtResult = DBHelper.ExecuteDataTable(sqllist);
        sb = new StringBuilder();
        sb.Append("{\"item\":[");
        for (int i = 0; i < dtResult.Rows.Count; i++)
        {
            sb.Append("{\"loginid\":\"" + dtResult.Rows[i]["loginid"].ToString() + "\",");
            sb.Append("\"username\":\"" + dtResult.Rows[i]["username"].ToString() + "\",");
            sb.Append("\"customername\":\"" + dtResult.Rows[i]["customername"].ToString() + "\",");
            sb.Append("\"phone\":\"" + dtResult.Rows[i]["phone"].ToString() + "\",");
            sb.Append("\"storeaddress\":\"" + dtResult.Rows[i]["storeaddress"].ToString() + "\"}");
            if (i < dtResult.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //作废
    public void zf(HttpContext context)
    {
        int retrun = 0;
        string remsg = "";
        string id = PageBase.ext_string(context.Request.Params["ids"]);
        string iscz = "select id from product where id='"+id+"' and isactive='Y'";
        DataTable  ishave= DBHelper.ExecuteDataTable(iscz);
        if (ishave.Rows.Count > 0)
        {
            string updatesp = "update product set isactive='N',updatetime='"+DateTime.Now.ToString()+"' where id="+id+"";
            retrun = DBHelper.ExecuteNonQuery(updatesp);
            if (retrun > 0)
            {
                remsg += "作废成功!";
            }
            else
            {
                remsg += "作废失败!";
            }
        }
        else
        {
            remsg += "商品不存在";
        }
        context.Response.Write("{\"message\":\"" + remsg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //修改商品信息
    public void update_product(HttpContext context)
    {
        int retrun = 0;
        string remsg = "";
        string id = PageBase.ext_string(context.Request.Params["ids"]);
        string spname = PageBase.ext_string(context.Request.Params["spname"]);
        string lsprice = PageBase.ext_string(context.Request.Params["lsprice"]);
        string jhprice = PageBase.ext_string(context.Request.Params["jhprice"]);
        string pfprice = PageBase.ext_string(context.Request.Params["pfprice"]);
        string qckc = PageBase.ext_string(context.Request.Params["qckc"]) == "" ? "0" : PageBase.ext_string(context.Request.Params["qckc"]);
        string huohao = PageBase.ext_string(context.Request.Params["huohao"]);
        string remark = PageBase.ext_string(context.Request.Params["remark"]);
        string SQLMaster = @"update [product] set
                            [name]='{0}'
                           ,[reprice]={1}
                           ,[buyprice]={2}
                           ,[pfprice]={3}
                           ,[qckc]={4}
                           ,[huohao]='{5}'
                           ,[remark]='{6}'
                           ,[isactive]='{7}'
                           where id={8}";

        SQLMaster = string.Format(SQLMaster, spname, lsprice, jhprice,pfprice, qckc, huohao, remark, "Y",id);
        retrun = DBHelper.ExecuteNonQuery(SQLMaster);
        if (retrun > 0)
        {
            remsg += "修改成功!";
        }
        else
        {
            remsg += "修改失败!";
        }

        context.Response.Write("{\"message\":\"" + remsg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //新建商品信息
    public void save_new(HttpContext context)
    {
        int retrun = 0;
        string remsg = "";
        string txt_lxname = PageBase.ext_string(context.Request.Params["txt_lxname"]);
        string txt_ltxh = PageBase.ext_string(context.Request.Params["txt_ltxh"]);
        string txt_lthw = PageBase.ext_string(context.Request.Params["txt_lthw"]);
        string txt_price = PageBase.ext_string(context.Request.Params["txt_price"]);
        string txt_xh = PageBase.ext_string(context.Request.Params["txt_xh"]);
        //string qckc = PageBase.ext_string(context.Request.Params["qckc"]) == "" ? "0" : PageBase.ext_string(context.Request.Params["qckc"]);
        //string huohao = PageBase.ext_string(context.Request.Params["huohao"]);
        //string remark = PageBase.ext_string(context.Request.Params["remark"]);
        string iscz = "select id from m_product where ltxh='"+txt_ltxh+"' and rtrim(ltrim(isactive))='Y'";
        DataTable  ishave= DBHelper.ExecuteDataTable(iscz);
        if (ishave.Rows.Count > 0)
        {
            remsg = "名称重复";
        }
        else
        {
            string SQLMaster = @"INSERT INTO [m_product]
                           ([ltlx]
                           ,[xh]
                           ,[ltxh]
                           ,[hw]
                           ,[price]
                           ,[isred]
                           ,[isactive]
                            )
                     VALUES
                           ('{0}'
                           ,'{1}'
                           ,'{2}'
                           ,'{3}'
                           ,'{4}'
                           ,'{5}'
                           ,'{6}'
                           );";

            SQLMaster = string.Format(SQLMaster, txt_lxname, txt_xh,txt_ltxh, txt_lthw,txt_price, "Y", "Y");
            retrun = DBHelper.ExecuteNonQuery(SQLMaster);
            if (retrun > 0)
            {
                remsg += "新增成功!";
            }
            else
            {
                remsg += "新增失败!";
            }
        }
        context.Response.Write("{\"message\":\"" + remsg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //新建商品信息
    public void save(HttpContext context)
    {
        int retrun = 0;
        string remsg = "";
        string spname = PageBase.ext_string(context.Request.Params["spname"]);
        string lsprice = PageBase.ext_string(context.Request.Params["lsprice"]);
        string jhprice = PageBase.ext_string(context.Request.Params["jhprice"]);
        string pfprice = PageBase.ext_string(context.Request.Params["pfprice"]);
        string qckc = PageBase.ext_string(context.Request.Params["qckc"]) == "" ? "0" : PageBase.ext_string(context.Request.Params["qckc"]);
        string huohao = PageBase.ext_string(context.Request.Params["huohao"]);
        string remark = PageBase.ext_string(context.Request.Params["remark"]);
        string iscz = "select id from product where name='"+spname+"' and isactive='Y'";
        DataTable  ishave= DBHelper.ExecuteDataTable(iscz);
        if (ishave.Rows.Count > 0)
        {
            remsg = "名称重复";
        }
        else
        {
            string SQLMaster = @"INSERT INTO [product]
                           ([name]
                           ,[reprice]
                           ,[buyprice]
                           ,[pfprice]
                           ,[qckc]
                           ,[huohao]
                           ,[remark]
                           ,[isactive]
                            )
                     VALUES
                           ('{0}'
                           ,'{1}'
                           ,'{2}'
                           ,'{3}'
                           ,'{4}'
                           ,'{5}'
                           ,'{6}'
                           ,'{7}'
                           );";

            SQLMaster = string.Format(SQLMaster, spname, lsprice, jhprice,pfprice, qckc, huohao, remark, "Y");
            retrun = DBHelper.ExecuteNonQuery(SQLMaster);
            if (retrun > 0)
            {
                remsg += "新增成功!";
            }
            else
            {
                remsg += "新增失败!";
            }
        }
        context.Response.Write("{\"message\":\"" + remsg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //保存零售信息
    public void salesave(HttpContext context)
    {
        int retrun = 0;
        string remsg = "";
        string id = PageBase.ext_string(context.Request.Params["ids"]);
        decimal? sl = PageBase.ext_decimal(context.Request.Params["sl"]);
        string iscz = "select * from product where id='"+id+"' and isactive='Y'";
        DataTable  ishave= DBHelper.ExecuteDataTable(iscz);
        //生成单据编号
        string sqldjbh = "declare @BH INT;declare @MID varchar(50);SELECT @BH=ISNULL(MAX(RIGHT(djbh,4)),0)+1 FROM sale WHERE LEFT(djbh,2)='LS'  AND  RIGHT(LEFT(djbh,4),2)=YEAR(GETDATE())%100;set @MID='LS'+CAST( CONVERT(VARCHAR(10),GETDATE(),12)*10000+@BH AS VARCHAR(30));SELECT @MID";
        DataTable dtResult = DBHelper.ExecuteDataTable(sqldjbh);
        string djbh = dtResult.Rows[0][0].ToString();
        if (ishave.Rows.Count > 0)
        {
            decimal? lsprice = PageBase.ext_decimal(ishave.Rows[0]["reprice"]) == null ? 0 : PageBase.ext_decimal(ishave.Rows[0]["reprice"]);
            decimal? jhprice = PageBase.ext_decimal(ishave.Rows[0]["buyprice"]) == null ? 0 : PageBase.ext_decimal(ishave.Rows[0]["buyprice"]);
            decimal? pfprice = PageBase.ext_decimal(ishave.Rows[0]["pfprice"]) == null ? 0 : PageBase.ext_decimal(ishave.Rows[0]["pfprice"]);
            string SQLMaster = @"INSERT INTO [sale_item]
                           ([djbh]
                           ,[productid]
                           ,[sl]
                           ,[lsprice]
                           ,[jhprice]
                           ,[pfprice]
                           ,[isactive]
                            )
                     VALUES
                           ('{0}'
                           ,'{1}'
                           ,{2}
                           ,{3}
                           ,{4}
                           ,{5}
                           ,'{6}'
                           );";
            SQLMaster = string.Format(SQLMaster, djbh, id, sl,lsprice,jhprice,pfprice, "Y");

            decimal? lsje =lsprice * sl;
            decimal? jhje =jhprice * sl;
            decimal? pfje = pfprice * sl;
            SQLMaster += @"INSERT INTO [sale]
                           ([djbh]
                           ,[lssl]
                           ,[lsje]
                           ,[jhje]
                           ,[pfje]
                           ,[state]
                           ,[isactive]
                            )
                     VALUES
                           ('{0}'
                           ,{1}
                           ,{2}
                           ,{3}
                           ,{4}
                           ,'{5}'
                           ,'{6}'
                           );";

            SQLMaster = string.Format(SQLMaster, djbh,sl, lsje,jhje,pfje, 2, "Y");
            retrun = DBHelper.ExecuteNonQuery(SQLMaster);
            if (retrun > 0)
            {
                remsg += "销售成功!";
            }
            else
            {
                remsg += "销售失败!";
            }
        }
        else
        {
            remsg += "商品不存在";
        }

        context.Response.Write("{\"message\":\"" + remsg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();

    }
    //保存采购信息
    public void buysave(HttpContext context)
    {
        int retrun = 0;
        string remsg = "";
        string id = PageBase.ext_string(context.Request.Params["ids"]);
        decimal? sl = PageBase.ext_decimal(context.Request.Params["sl"]);
        string iscz = "select * from product where id='"+id+"' and isactive='Y'";
        DataTable  ishave= DBHelper.ExecuteDataTable(iscz);
        //生成单据编号
        string sqldjbh = "declare @BH INT;declare @MID varchar(50);SELECT @BH=ISNULL(MAX(RIGHT(djbh,4)),0)+1 FROM purchase WHERE LEFT(djbh,2)='CG'  AND  RIGHT(LEFT(djbh,4),2)=YEAR(GETDATE())%100;set @MID='CG'+CAST( CONVERT(VARCHAR(10),GETDATE(),12)*10000+@BH AS VARCHAR(30));SELECT @MID";
        DataTable dtResult = DBHelper.ExecuteDataTable(sqldjbh);
        string djbh = dtResult.Rows[0][0].ToString();
        if (ishave.Rows.Count > 0)
        {
            decimal? lsprice = PageBase.ext_decimal(ishave.Rows[0]["reprice"]) == null ? 0 : PageBase.ext_decimal(ishave.Rows[0]["reprice"]);
            decimal? jhprice = PageBase.ext_decimal(ishave.Rows[0]["buyprice"]) == null ? 0 : PageBase.ext_decimal(ishave.Rows[0]["buyprice"]);
            decimal? pfprice = PageBase.ext_decimal(ishave.Rows[0]["pfprice"]) == null ? 0 : PageBase.ext_decimal(ishave.Rows[0]["pfprice"]);

            string SQLMaster = @"INSERT INTO [purchase_item]
                           ([djbh]
                           ,[productid]
                           ,[sl]
                           ,[lsprice]
                           ,[jhprice]
                           ,[pfprice]
                           ,[isactive]
                            )
                     VALUES
                           ('{0}'
                           ,'{1}'
                           ,{2}
                           ,{3}
                           ,{4}
                           ,{5}
                           ,'{6}'
                           );";
            SQLMaster = string.Format(SQLMaster, djbh, id, sl,lsprice,jhprice,pfprice, "Y");

            decimal? lsje =lsprice * sl;
            decimal? jhje =jhprice * sl;
            decimal? pfje =pfprice * sl;
            SQLMaster += @"INSERT INTO [purchase]
                           ([djbh]
                           ,[cgsl]
                           ,[bzje]
                           ,[jhje]
                           ,[pfje]
                           ,[state]
                           ,[isactive]
                            )
                     VALUES
                           ('{0}'
                           ,{1}
                           ,{2}
                           ,{3}
                           ,{4}
                           ,'{5}'
                           ,'{6}'
                           );";

            SQLMaster = string.Format(SQLMaster, djbh,sl, lsje,jhje,pfje, 2, "Y");
            retrun = DBHelper.ExecuteNonQuery(SQLMaster);
            if (retrun > 0)
            {
                remsg += "采购成功!";
            }
            else
            {
                remsg += "采购失败!";
            }
        }
        else
        {
            remsg += "商品不存在";
        }
        context.Response.Write("{\"message\":\"" + remsg + "\"}");
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    //获取商品信息new
    public void getlistnew(HttpContext context)
    {

        string sqllist = @"select id,ltlx,ltxh,hw,Convert(decimal(18,0),price) price,rtrim(ltrim(isred)) isred,
createtime,updatetime,rtrim(ltrim(isactive)) isactive from m_product where rtrim(ltrim(isactive))='Y' order by xh";
        DataTable dtResult = DBHelper.ExecuteDataTable(sqllist);
        sb = new StringBuilder();
        sb.Append("{\"item\":[");
        for (int i = 0; i < dtResult.Rows.Count; i++)
        {
            sb.Append("{\"id\":\"" + dtResult.Rows[i]["id"].ToString() + "\",");
            sb.Append("\"ltlx\":\"" + dtResult.Rows[i]["ltlx"].ToString() + "\",");
            sb.Append("\"ltxh\":\"" + dtResult.Rows[i]["ltxh"].ToString() + "\",");
            sb.Append("\"hw\":\"" + dtResult.Rows[i]["hw"].ToString() + "\",");
            sb.Append("\"price\":\"" + dtResult.Rows[i]["price"].ToString() + "\",");
            sb.Append("\"isred\":\"" + dtResult.Rows[i]["isred"].ToString() + "\",");
            sb.Append("\"createtime\":\"" + dtResult.Rows[i]["createtime"].ToString() + "\",");
            sb.Append("\"updatetime\":\"" + dtResult.Rows[i]["updatetime"].ToString() + "\",");
            sb.Append("\"isactive\":\"" + dtResult.Rows[i]["isactive"].ToString() + "\"}");
            if (i < dtResult.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }

    //获取商品详细信息
    public void getlist_mx(HttpContext context)
    {
        string id = PageBase.ext_string(context.Request.Params["ids"]);
        string sqllist = @"select a.id,a.name,a.reprice,a.buyprice,a.pfprice,a.huohao,
a.remark,a.createtime,a.qckc,isnull(a.qckc,0)+isnull(b.cgsl,0)-isnull(c.xssl,0) kc
,isnull(b.cgsl,0) cgsl,isnull(c.xssl,0) xssl from product a 
left join (select productid,sum(sl) cgsl from purchase_item  where isactive='Y'  group by productid)b on a.id=b.productid
left join (select productid,sum(sl) xssl from sale_item  where isactive='Y'  group by productid)c on a.id=c.productid
where a.id={0} and a.isactive='Y'
group by a.id,a.name,a.qckc,a.reprice,a.buyprice,a.huohao,a.remark,a.createtime,c.xssl,b.cgsl,a.pfprice
order by a.createtime desc";
        sqllist = string.Format(sqllist,id);
        DataTable dtResult = DBHelper.ExecuteDataTable(sqllist);
        sb = new StringBuilder();
        sb.Append("{\"item\":[");
        for (int i = 0; i < dtResult.Rows.Count; i++)
        {
            sb.Append("{\"id\":\"" + dtResult.Rows[i]["id"].ToString() + "\",");
            sb.Append("\"name\":\"" + dtResult.Rows[i]["name"].ToString() + "\",");
            sb.Append("\"reprice\":\"" + dtResult.Rows[i]["reprice"].ToString() + "\",");
            sb.Append("\"buyprice\":\"" + dtResult.Rows[i]["buyprice"].ToString() + "\",");
            sb.Append("\"pfprice\":\"" + dtResult.Rows[i]["pfprice"].ToString() + "\",");
            sb.Append("\"qckc\":\"" + dtResult.Rows[i]["qckc"].ToString() + "\",");
            sb.Append("\"kc\":\"" + dtResult.Rows[i]["kc"].ToString() + "\",");
            sb.Append("\"cgsl\":\"" + dtResult.Rows[i]["cgsl"].ToString() + "\",");
            sb.Append("\"xssl\":\"" + dtResult.Rows[i]["xssl"].ToString() + "\",");
            sb.Append("\"huohao\":\"" + dtResult.Rows[i]["huohao"].ToString() + "\",");
            sb.Append("\"remark\":\"" + dtResult.Rows[i]["remark"].ToString() + "\"}");
            if (i < dtResult.Rows.Count - 1)
            {
                sb.Append(",");
            }
        }
        sb.Append("]}");
        context.Response.Write(sb.ToString());
        context.Response.ContentType = "text/json";
        context.Response.End();
    }
    public class GetDate
    {
        public List<main> ArrayObj_main { get; set; }//主表信息
        public List<mx> ArrayObj_mx { get; set; }//明细信息
    }
    public class main
    {
        //单据编号
        public string id;
        public string ID
        {
            get { return id; }
            set { id = value; }
        }
        //单据编号
        public string docno;
        public string DOCNO
        {
            get { return docno; }
            set { docno = value; }
        }
        //店仓编号
        public string userid;
        public string USERID
        {
            get { return userid; }
            set { userid = value; }
        }
        //店仓编号
        public string customerCode;
        public string CUSTOMERCODE
        {
            get { return customerCode; }
            set { customerCode = value; }
        }
        //收货人姓名
        public string shr;
        public string SHR
        {
            get { return shr; }
            set { shr = value; }
        }
        //手机号
        public string phone;
        public string PHONE
        {
            get { return phone; }
            set { phone = value; }
        }
        //企微手机号
        public string mobile;
        public string MOBILE
        {
            get { return mobile; }
            set { mobile = value; }
        }
        //收货人地址
        public string address;
        public string ADDRESS
        {
            get { return address; }
            set { address = value; }
        }
        //备注
        public string remark;
        public string REMARK
        {
            get { return remark; }
            set { remark = value; }
        }


        //快递公司
        public string txt_kdgs;
        public string TXT_KDGS
        {
            get { return txt_kdgs; }
            set { txt_kdgs = value; }
        }
        //快递单号
        public string txt_kddh;
        public string TXT_KDDH
        {
            get { return txt_kddh; }
            set { txt_kddh = value; }
        }
        //发货人
        public string txt_kdfhr;
        public string TXT_KDFHR
        {
            get { return txt_kdfhr; }
            set { txt_kdfhr = value; }
        }
        //发货人联系电话
        public string txt_kdtel;
        public string TXT_KDTEL
        {
            get { return txt_kdtel; }
            set { txt_kdtel = value; }
        }

    }
    //尺码
    public class mx
    {
        //tmid
        public string tmid;
        public string TMID
        {
            get { return tmid; }
            set { tmid = value; }
        }

        //数量
        public int? sl;
        public int? SL
        {
            get { return sl; }
            set { sl = value; }
        }
        //备注
        public string mark;
        public string MARK
        {
            get { return mark; }
            set { mark = value; }
        }

        public string imageurl;
        public string IMAGEURL
        {
            get { return imageurl; }
            set { imageurl = value; }
        }

    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}